﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XMK.Utils;
using System.Text;
using System.IO;
using System.Configuration;
namespace XMK.Tadong.ServiceWeb.Handlers
{
    /// <summary>
    /// upload 的摘要说明
    /// </summary>
    public class upload : IHttpHandler
    {
        private string fullFileName = string.Empty;
        private string orginalFileName = string.Empty;
        private string[] fullFileNames;
        private string[] orginalFileNames;
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string fileType = context.Request["fileType"];
                if (String.IsNullOrEmpty(fileType))
                {
                    setResponse(JsonHelper.ToJson(new { status = 1, msg = "plese set file ype！" }));
                }
                else
                {
                    if (UploadFile(fileType))
                    {
                        context.Response.Write(JsonHelper.ToJson(new { status = 0, msg = "upload success。", realName = string.Join(";", orginalFileNames), fileName = string.Join(";", fullFileNames) }));
                    }
                    else
                    {
                        context.Response.Write(JsonHelper.ToJson(new { status = 1, msg = "upload false" }));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("[error:" + DateTime.Now.ToString() + "][fileType:" + context.Request["filetype"].ToString() + "][mesg：" + ex.Message + "]");
                context.Response.Write(JsonHelper.ToJson(new { status = 1, msg = "upload false" }));
                context.Response.Flush();
                context.Response.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private bool UploadFile(string fileType)
        {
            int fileCount =  HttpContext.Current.Request.Files.Count;
            if (fileType == "feedback")
            {
                if (fileCount > 0)
                {
                    orginalFileNames = new string[fileCount];
                    fullFileNames = new string[fileCount];
                    try
                    {
                        for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                        {
                            Random random = new Random(DateTime.Now.Minute);
                            string physicalPath = HttpContext.Current.Server.MapPath("~/attach");

                            orginalFileName = HttpContext.Current.Request.Files[i].FileName;
                            orginalFileNames[i] = orginalFileName;

                            string filename = DateTime.Now.ToString("ddHHmmssffff") + "_" + random.Next(10000).ToString() + GetExtension(orginalFileName);
                            string middelName = DateTime.Now.ToString(@"yyyy\/M");
                            fullFileName = middelName + "/" + filename;// 保存到数据库
                            string _fullFileName = "/" + fileType + "/" + middelName + "/" + filename;//完整路径
                            string FolderName = "/" + fileType + "/" + middelName;//文件夹
                            fullFileNames[i] = fullFileName;
                            if (!Directory.Exists(physicalPath + FolderName))
                            {
                                Directory.CreateDirectory(physicalPath + FolderName);
                            }
                            HttpContext.Current.Request.Files[i].SaveAs(physicalPath + _fullFileName);
                        }
                        return true;
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog("[error:" + DateTime.Now.ToString() + "][fileName:" + fileType + "\\" + fullFileName + "][mesg：" + ex.Message + "]");
                        return false;
                    }

                }
            }
            else if (fileType == "prePic")
            {
                if (fileCount > 0)
                {
                    orginalFileNames = new string[fileCount];
                    fullFileNames = new string[fileCount];
                    try
                    {
                        for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                        {
                            Random random = new Random(DateTime.Now.Minute);
                            string physicalPath = HttpContext.Current.Server.MapPath("~");

                            //physicalPath = physicalPath.Substring(0, physicalPath.LastIndexOf("\\"));
                            physicalPath = "D:\\TaDongDoc\\PRE_IMAGES";
                            orginalFileName = HttpContext.Current.Request.Files[i].FileName;
                            orginalFileNames[i] = orginalFileName;

                            string filename = DateTime.Now.ToString("ddHHmmssffff") + "_" + random.Next(10000).ToString() + GetExtension(orginalFileName);
                            // string middelName = DateTime.Now.ToString(@"yyyy\/M");
                            fullFileName = filename;// 保存到数据库
                            string _fullFileName = physicalPath + "/" + filename;//完整路径
                            string FolderName = "/" + fileType;//文件夹
                            fullFileNames[i] = fullFileName;
                            if (!Directory.Exists(physicalPath))
                            {
                                Directory.CreateDirectory(physicalPath);
                            }
                            HttpContext.Current.Request.Files[i].SaveAs(_fullFileName);
                        }
                        return true;
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog("[error:" + DateTime.Now.ToString() + "][fileName:" + fileType + "\\" + fullFileName + "][mesg：" + ex.Message + "]");
                        return false;
                    }

                }
            }
            else
            {
                if (fileCount > 0)
                {
                    orginalFileNames = new string[fileCount];
                    fullFileNames = new string[fileCount];
                    try
                    {
                        for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                        {
                            Random random = new Random(DateTime.Now.Minute);
                            string physicalPath = HttpContext.Current.Server.MapPath("~");

                            physicalPath=physicalPath.Substring(0,physicalPath.LastIndexOf("\\"));
                            physicalPath=physicalPath+"\\XMK.Tadong.Web\\WebFileExplorer\\images\\ico\\";
                            orginalFileName = HttpContext.Current.Request.Files[i].FileName;
                            orginalFileNames[i] = orginalFileName;

                            string filename = DateTime.Now.ToString("ddHHmmssffff") + "_" + random.Next(10000).ToString() + GetExtension(orginalFileName);
                           // string middelName = DateTime.Now.ToString(@"yyyy\/M");
                            fullFileName = filename;// 保存到数据库
                            string _fullFileName = "/" + fileType + "/" + filename;//完整路径
                            string FolderName = "/" + fileType;//文件夹
                            fullFileNames[i] = fullFileName;
                            if (!Directory.Exists(physicalPath + FolderName))
                            {
                                Directory.CreateDirectory(physicalPath + FolderName);
                            }
                            HttpContext.Current.Request.Files[i].SaveAs(physicalPath + _fullFileName);
                        }
                        return true;
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog("[error:" + DateTime.Now.ToString() + "][fileName:" + fileType + "\\" + fullFileName + "][mesg：" + ex.Message + "]");
                        return false;
                    }

                }

            }
            return false;
        }

        private string GetExtension(string filename)
        {
            FileInfo fileInfo = new FileInfo(filename);
            return fileInfo.Extension;
        }
        private void setResponse(string result)
        {
            byte[] bytes = Encoding.GetEncoding("gb2312").GetBytes(result);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = false;
            HttpContext.Current.Response.Charset = "gb2312";
            HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("gb2312");
            HttpContext.Current.Response.ContentType = "text/plain";
            HttpContext.Current.Response.AppendHeader("Content-Length", bytes.Length.ToString());
            HttpContext.Current.Response.Write(bytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Close();
        }
    }
}